package com.tcu.cors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class CorsConfig  {

    @Bean
    public CorsConfiguration corsConfiguration(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
//        with session crossOrigin
        corsConfiguration.setAllowedHeaders(List.of("*"));

        corsConfiguration.setAllowedMethods(List.of("*"));
//        带session的跨域 不能为 *
        corsConfiguration.setAllowedOrigins(List.of("http://localhost:9999"));
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(CorsConfiguration corsConfiguration) {

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", corsConfiguration);
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}
